package com.jinyang.jetpackdemo.util.http.interceptor

import com.jinyang.jetpackdemo.util.LjyLogUtil
import kotlin.Throws
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.charset.UnsupportedCharsetException
import java.util.concurrent.TimeUnit

/**
 * @Author: LiuJinYang
 * @CreateDate: 2020/5/20
 * 日志拦截器
 */
class LoggingInterceptor : Interceptor {
    private val UTF8 = StandardCharsets.UTF_8
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBody = request.body()
        var body: String? = null
        if (requestBody != null) {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset = UTF8
            val contentType = requestBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(UTF8)
            }
            body = buffer.readString(charset)
        }

//        LogUtil.d(String.format("发送请求\nmethod：%s\nurl：%s\nheaders: \n%sbody：\n%s",
//                request.method(), request.url(), request.headers(), body));
        val startNs = System.nanoTime()
        val response = chain.proceed(request)
        val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
        val responseBody = response.body()
        var rBody: String? = null
        if (responseBody!!.source() != null) {
            val source = responseBody.source()
            source.request(Long.MAX_VALUE) // Buffer the entire body.
            val buffer = source.buffer()
            var charset = UTF8
            val contentType = responseBody.contentType()
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8)
                } catch (e: UnsupportedCharsetException) {
                    e.printStackTrace()
                }
            }
            rBody = buffer.clone().readString(charset)
        }
        LjyLogUtil.d(
            String.format(
                "收到响应 %s %s %sms\n请求url：%s\n请求方式：%s\n请求body：\n%s\n请求header:\n%s\n响应body：\n%s",
                response.code(),
                response.message(),
                tookMs,
                response.request().url(),
                request.method(),
                body,
                request.headers(),
                rBody
            )
        )
        return response
    }
}